package com.sh.pangea.dsa.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.sh.lib.dsa.bean.analyzeresult.LinearItem;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.AnalyzeIntentUtil;
import com.sh.pangea.dsa.Utils.SildingFinishLayout;
import com.sh.pangea.dsa.bean.AnalyzeResult;
import com.sh.pangea.dsa.bean.MenuInfo;
import com.sh.pangea.dsa.observer.AnalyzeResultObservable;
import com.sh.pangea.dsa.observer.AnalyzeResultObserver;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 饼状图图表
 */
public class PiePolylineChartActivity extends Activity implements AnalyzeResultObserver {
    private String TAG = "TGH";
    @BindView(R.id.pie_chart)
    PieChart pieChart;
    @BindView(R.id.sildingFinishLayout_pie)
    SildingFinishLayout sildingFinishLayout_pie;
    @BindView(R.id.pie_linearlayout)
    LinearLayout pie_linearlayout;
    @BindView(R.id.pie_chart_title)
    TextView pie_chart_title;

    private AnalyzeResult mAnalyzeResult = null;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String titleGraph = mAnalyzeResult.getTitleGraph();
                    List<LinearItem> linearItems = mAnalyzeResult.getyForGraph();
                    if (titleGraph == null) {
                        titleGraph = "";
                    }
                    pie_chart_title.setText(titleGraph);
//                    generateDataPie(linearItems, titleGraph);
                    generateDataPie();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.fragment_pie_polyline_chart);
        ButterKnife.bind(this);
        AnalyzeResultObservable.getInstance().registerObserver(this);
        initView();
        getIntetn();
    }

    private void initView() {
        setPieChart(pieChart);
        sildingFinishLayout_pie.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                PiePolylineChartActivity.this.finish();
            }
        });
        // touchView要设置到ListView上面
        sildingFinishLayout_pie.setTouchView(pie_linearlayout);
        sildingFinishLayout_pie.setTouchView(pie_chart_title);
    }

    private void getIntetn() {
        Intent intent = this.getIntent();
        MenuInfo parentInfo = (MenuInfo) intent.getSerializableExtra("parentInfo");
        MenuInfo groupInfo = (MenuInfo) intent.getSerializableExtra("groupInfo");
        MenuInfo childInfo = (MenuInfo) intent.getSerializableExtra("childInfo");
        groupInfo.getChartType();
        Log.i(TAG, "PiePolylineChartActivity   getIntetn  : " + parentInfo + "   " + groupInfo + "  " + childInfo);
        AnalyzeIntentUtil.getInstance(this).analyzeIntent(parentInfo, groupInfo, childInfo);
    }

    private void setPieChart(PieChart pieChart) {
//        //用自带的百分比算法
//        pieChart.setUsePercentValues(true);
//        pieChart.getDescription().setEnabled(false);
//        //设置整个饼状图是空心还是实心
//        pieChart.setDrawHoleEnabled(false);
//        pieChart.setExtraOffsets(20f, 5.f, 20f, 5.f);
//        //图标log显示在中心
//        pieChart.setDrawCenterText(false);
//        /**
//         *触摸是否可以旋转以及松手后旋转的度数
//         */
//        pieChart.setRotationAngle(300);
//        // enable rotation of the chart by touch
//        pieChart.setRotationEnabled(true);
//        pieChart.setHighlightPerTapEnabled(true);
//        //饼形图上是否显示每个模块的X轴的值
//        pieChart.setDrawEntryLabels(false);
//        pieChart.animateX(1000);
//        //设置数据为空时显示的描述文字
//        pieChart.setNoDataText("暂时没有数据！");
//        Legend l = pieChart.getLegend();
//        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
//        l.setOrientation(Legend.LegendOrientation.VERTICAL);
//        l.setDrawInside(true);
//        l.setEnabled(true);
//
//
//        //点击没柱显示数据
//        XYMarkerViewPiePoylineChart mv = new XYMarkerViewPiePoylineChart(this, mIAxisValueFormatter_X);
//        mv.setChartView(pieChart); // For bounds control
//        pieChart.setMarker(mv); // Set the marker to the chart
////        pieChart.setOnChartValueSelectedListener(mOnChartValueSelectedListener);



        pieChart.setUsePercentValues(false);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5, 10, 5, 5);

        pieChart.setDragDecelerationFrictionCoef(0.95f);


        pieChart.setCenterText(generateCenterSpannableText());

        pieChart.setExtraOffsets(55.f, 0.f, 55.f, 0.f);

        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);

        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);

        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);

        pieChart.setDrawCenterText(true);

        pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);

        //pieChart.setOnChartValueSelectedListener(this);


        pieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);

        Legend l = pieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);

    }

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.5f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.65f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    private final IAxisValueFormatter mIAxisValueFormatter_X = new IAxisValueFormatter() {

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            Log.i(TAG, "getFormattedValue: " + value + "      " + axis);
            return ((int) value) + "";
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };


    protected String[] mParties = new String[]{
            "Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H",
            "Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P",
            "Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
            "Party Y", "Party Z"
    };


    private void generateDataPie() {
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        for (int i = 0; i < 25; i++) {
            if(i== 2){

            }else{
                entries.add(new PieEntry(i, mParties[i % mParties.length]));
            }
        }
        PieDataSet dataSet = new PieDataSet(entries, "数据的饼状图");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);


        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.1f);
        dataSet.setValueLinePart2Length(0.2f);
        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        pieChart.setData(data);

        // undo all highlights
        pieChart.highlightValues(null);

        pieChart.invalidate();
    }


//    {
//        yForGraph=[
//        RatioItem{
//        name='互联网',
//                y=748
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@3adc3624,
//            RatioItem{
//        name='太原有线',
//                y=66
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@2c1a358d,
//            RatioItem{
//        name='秦皇岛有线',
//                y=61
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@3b87f342,
//            RatioItem{
//        name='江西有线',
//                y=59
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@2c0cdf53,
//            RatioItem{
//        name='创维海通',
//                y=49
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@3ab89090,
//            RatioItem{
//        name='珠江数码',
//                y=33
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@1c019d89,
//            RatioItem{
//        name='湖南有线',
//                y=25
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@ba6018e,
//        RatioItem{
//        name='研发环境',
//                y=3
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@bfc1daf,
//        RatioItem{
//        name='石家庄广电',
//                y=2
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@fbe25bc,
//        RatioItem{
//        name='贵州有线',
//                y=1
//    }com.sh.lib.dsa.bean.analyzeresult.RatioItem@edd8945
//        ]
//    }BaseAnalyzeResult{
//        message='0',
//                nowDate='null',
//                minDate='null',
//                queryDate='null',
//                weekly='null',
//                titleGraph='健康视频播放次数各地区占比图'
//    }

    public List<LinearItem> set(){
        List<LinearItem> linearItems = new ArrayList<>();
        LinearItem mLinearItem1 = new LinearItem();
        mLinearItem1.setName("互联网");
        mLinearItem1.setYAxis(748);
        linearItems.add(mLinearItem1);
        LinearItem mLinearItem2 = new LinearItem();
        mLinearItem2.setName("太原有线");
        mLinearItem2.setYAxis(66);
        linearItems.add(mLinearItem2);
        LinearItem mLinearItem3 = new LinearItem();
        mLinearItem3.setName("秦皇岛有线");
        mLinearItem3.setYAxis(61);
        linearItems.add(mLinearItem3);
        LinearItem mLinearItem4 = new LinearItem();
        mLinearItem4.setName("江西有线");
        mLinearItem4.setYAxis(59);
        linearItems.add(mLinearItem4);
        LinearItem mLinearItem5 = new LinearItem();
        mLinearItem5.setName("创维海通");
        mLinearItem5.setYAxis(49);
        linearItems.add(mLinearItem5);
        LinearItem mLinearItem6 = new LinearItem();
        mLinearItem6.setName("珠江数码");
        mLinearItem6.setYAxis(33);
        linearItems.add(mLinearItem6);
        LinearItem mLinearItem7 = new LinearItem();
        mLinearItem7.setName("湖南有线");
        mLinearItem7.setYAxis(25);
        linearItems.add(mLinearItem7);
        LinearItem mLinearItem8 = new LinearItem();
        mLinearItem8.setName("研发环境");
        mLinearItem8.setYAxis(3);
        linearItems.add(mLinearItem8);
        LinearItem mLinearItem9 = new LinearItem();
        mLinearItem9.setName("石家庄广电");
        mLinearItem9.setYAxis(2);
        linearItems.add(mLinearItem9);
        LinearItem mLinearItem10 = new LinearItem();
        mLinearItem10.setName("贵州有线");
        mLinearItem10.setYAxis(1);
        linearItems.add(mLinearItem10);
        return linearItems;
    }


    private void generateDataPie(List<LinearItem> linearItems, String nameGraph) {
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        if (linearItems != null && linearItems.size() > 0) {
            LinearItem linearItem;
            for (int i = 0; i < linearItems.size(); i++) {
                linearItem = linearItems.get(i);
                float yAxis = (float) linearItem.getYAxis();
                if (yAxis == 2.0f) {
                    Log.i(TAG, "generateDataPie: 为什么不行  ");
                    yAxis = 3f;
                }
                entries.add(new PieEntry(yAxis, linearItem.getName()));
            }
            PieDataSet dataSet = new PieDataSet(entries, /*nameGraph*/"");
            dataSet.setSliceSpace(3f);
            dataSet.setSelectionShift(5f);
            // add a lot of colors
            ArrayList<Integer> colors = new ArrayList<Integer>();
            for (int c : ColorTemplate.VORDIPLOM_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.JOYFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.COLORFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.LIBERTY_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.PASTEL_COLORS)
                colors.add(c);

            colors.add(ColorTemplate.getHoloBlue());
            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            dataSet.setValueLinePart1OffsetPercentage(80.f);
            //设置每个扇形数值上黑线的长度
            dataSet.setValueLinePart1Length(0.5f);
            dataSet.setValueLinePart2Length(0.5f);
            //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

            PieData data = new PieData(dataSet);
            Log.i(TAG, "generateDataPie:   " + entries);
            //设置百分比显示
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(8f);
            data.setValueTextColor(Color.BLACK);
            pieChart.setData(data);

            // undo all highlights
            pieChart.highlightValues(null);
            pieChart.invalidate();
        }
    }


    /**
     * 返回
     **/
    @OnClick(R.id.analyze_back)
    public void onBackClick(View view) {
        this.finish();
    }


    /**
     * 重置
     */
    @OnClick(R.id.analyze_reset)
    public void onResetClick(View view) {
        pieChart.animateY(3000);
    }

    /**
     * 分享
     */
    @OnClick(R.id.analyze_share)
    public void onShareClick(View view) {
        Log.i(TAG, "onShareClick: ");
        Bitmap bit = null;
        switch (AnalyzeIntentUtil.getInstance(PiePolylineChartActivity.this).getIconType()) {
            case AnalyzeIntentUtil.LINAR_CHART://折线图
                break;
            case AnalyzeIntentUtil.BAR_CHART://柱状图
                break;
            case AnalyzeIntentUtil.PIE_CHART://扇形图
                pieChart.saveToGallery("thumbnail" /*+ System.currentTimeMillis()*/, 100);
                bit = pieChart.getChartBitmap();
                break;
            default:
                Log.i(TAG, "showIconType: 没有匹配的图表");
                break;
        }
//        if (mAnalyzeResult != null) {
        ShareAction shareAction = new ShareAction(PiePolylineChartActivity.this);
        shareAction.withTitle(/*mAnalyzeResult.getTitleGraph()*/"");
        shareAction.withText(/*mAnalyzeResult.getNameGraph()*/"");
        shareAction.withTargetUrl("http://www.skyworth-hightong.com");

        if (bit != null) {
            shareAction.withMedia(new UMImage(this.getApplicationContext(), bit));
        }
        shareAction.setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener).open();
//        } else {
//            Log.i(TAG, "onShareClick: mAnalyzeResult is null");
//        }
    }

    private final UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            Log.i(TAG, "分享返回值  onResult: " + share_media);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            Log.i(TAG, "分享失败 onError: " + share_media);
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            Log.i(TAG, "取消分享  onCancel: " + share_media);
        }
    };

    @Override
    public void onAnalyzeResult(int code, String error, AnalyzeResult analyzeResult) {
        Log.i("Main", "*********饼状图   onAnalyzeResult   code:" + code + "   error:" + error);
        Log.i("Main", "*********饼状图   onAnalyzeResult   analyzeResult:" + analyzeResult);
        mAnalyzeResult = analyzeResult;
        mHandler.sendEmptyMessage(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AnalyzeResultObservable.getInstance().unregisterObserver(this);
    }
}
